﻿<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Transaction.recCorporateActionhandler" %>

using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using System.Configuration;
using SIPO.Library.DataAccess.Transaction;
using SIPO.Library.DomainObject.Transaction;
using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DataAccess.Administration.Catalog;
using SIPO.Library.DomainObject.Administration;
using SIPO.Library.DomainObject.Administration.UserManagement;
using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.Enum;
using SIPO.Web.Support;

using Newtonsoft.Json.Linq;

namespace SIPO.Web.AjaxHandler.Transaction
{

    public class recCorporateActionhandler : SIPO.Web.BaseHandler
    {
        private recCorporateActionRepo recCorporateActionDal = new recCorporateActionRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recTransactionTypeRepo recTransactionTypeDal = new recTransactionTypeRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recBillingRepo recBillingRepo = new recBillingRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recInvoiceRepo recInvoiceRepo = new recInvoiceRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private string MethodName = string.Empty;
        private recDayOffRepo recDayOffDal = new recDayOffRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        
        
        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];
            context.Response.Clear();
            context.Response.Buffer = true;

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context, jObj));
                    break;
                case ("update"):
                    context.Response.Write(Update(context, jObj));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context, jObj));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();
        }

        private string Insert(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();
            string captchaHash = (string)jo["CaptchaHash"];
            string captcha = (string)jo["Captcha"];
            bool isExpired = string.IsNullOrEmpty(jo["IsExpired"].ToString()) ? false : (jo["IsExpired"].ToString().Equals("1") ? true : false);

            if ((Helper.HashCaptcha(captcha).Equals(captchaHash) || (captcha == "internal")) && (!isExpired)) // Check input captcha = Generated captcha
            {
                try
                {
                    //recTransactionType transType = recTransactionTypeDal.GetByLikeTransTypeName("aksi korporasi");
                    recTransactionType transType = recTransactionTypeDal.GetByTransTypeCode(4);
                    recCorporateAction obj = new recCorporateAction();

                    if (jo["CorporateActionTypeID"].ToString() != "")
                        obj.CorporateActionTypeID = (short)jo["CorporateActionTypeID"];
                    if (jo["DebtorID"].ToString() != "")
                        obj.DebtorID = (int)jo["DebtorID"];
                    if (jo["ImpositionValue"].ToString() != "")
                        obj.ImpositionValue = Helper.ToDecimal(jo["ImpositionValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);

                    obj.CorporateActionDate = DateTime.Now;
                    obj.CorporateName = (string)jo["CorporateName"];
                    obj.CorporateSector = (string)jo["CorporateSector"];

                    obj.NPWP = (string)jo["NPWP"];
                    obj.Address1 = (string)jo["Address1"];
                    obj.Address2 = (string)jo["Address2"];
                    obj.Address3 = (string)jo["Address3"];
                    if (jo["RegionID"].ToString() != "")
                        obj.RegionID = Convert.ToInt32(jo["RegionID"]);
                    if (jo["CityID"].ToString() != "")
                        obj.CityID = Convert.ToInt32(jo["CityID"]);
                    if (jo["ZipCode"].ToString() != "")
                        obj.ZipCode = (string)jo["ZipCode"];
                    obj.Email = (string)jo["Email"];
                    obj.Phone = (string)jo["Phone"];
                    obj.Fax = (string)jo["Fax"];
                    obj.Website = (string)jo["Website"];

                    if (jo["ImpositionBaseID"].ToString() != "")
                        obj.ImpositionBaseID = (short)jo["ImpositionBaseID"];

                    obj.InvoiceDate = DateTime.Now;

                    obj.CreateDate = DateTime.Now;
                    obj.CreateBy = base.UserLoggedIn;

                    // BILLING
                    recBilling objBilling = new recBilling();
                    objBilling.TransTypeID = (short)transType.TransTypeID;
                    objBilling.BillingDate = DateTime.Now;

                    var termDay = (short)transType.TermDay;
                    objBilling.DueDate = recDayOffDal.GetDueDate(DateTime.Now.AddDays(termDay).ToString("yyyyMMdd"));    //DateTime.Now.AddDays(termDay);
                    objBilling.ForPayment = (string)jo["ForPayment"];

                    if (jo["InvoiceValue"].ToString() != "")
                    {
                        objBilling.Value = Helper.ToDecimal(jo["InvoiceValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                        objBilling.Balance = Helper.ToDecimal(jo["InvoiceValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    }

                    if (jo["TariffID"].ToString() != "")
                        objBilling.TariffID = Convert.ToInt32(jo["TariffID"]);

                    objBilling.CreatedDate = DateTime.Now;
                    objBilling.CreatedBy = base.UserLoggedIn;

                    // INVOICE
                    recInvoice objInvoice = new recInvoice();
                    objInvoice.InvoiceDate = DateTime.Now;
                    //ambil bank ID dari subsector
                    int sectorid = 0;
                    recSubSectorRepo recSubSectorDal = new recSubSectorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                    recSectorRepo recSectorDal = new recSectorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                    recSector sector = recSectorDal.GetBySectorCode(Convert.ToInt32(jo["SectorCode"]));
                    if (sector != null)
                        sectorid = sector.SectorID;
                    recSubSector objSubSector = recSubSectorDal.GetBySubSectorCode(Convert.ToInt32(jo["SubSectorCode"]), sectorid);
                    if (objSubSector != null)
                    {
                        objInvoice.BankID = (short)objSubSector.BankID;
                    }

                    //end
                    //objInvoice.BankID = (short)transType.BankID;

                    objInvoice.BeSpelled = (string)jo["BeSpelled"]; ;

                    if (jo["InvoiceValue"].ToString() != "")
                        objInvoice.InvoiceValue = Helper.ToDecimal(jo["InvoiceValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);

                    objInvoice.CreatedDate = DateTime.Now;
                    objInvoice.CreatedBy = base.UserLoggedIn;

                    // INVOICE DETAIL
                    recInvoiceDetail objInvoiceDetail = new recInvoiceDetail();
                    if (jo["TariffID"].ToString() != "")
                        objInvoiceDetail.TariffID = Convert.ToInt32(jo["TariffID"]);

                    if (jo["InvoiceValue"].ToString() != "")
                        objInvoiceDetail.Value = Helper.ToDecimal(jo["InvoiceValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);

                    objInvoiceDetail.DueDate = DateTime.Now.AddDays(termDay);
                    objInvoiceDetail.ForPayment = (string)jo["ForPayment"];

                    objInvoiceDetail.BillingNo = objBilling.BillingNo;
                    objInvoiceDetail.TransTypeID = (short)transType.TransTypeID;

                    objInvoiceDetail.CreatedDate = DateTime.Now;
                    objInvoiceDetail.CreatedBy = base.UserLoggedIn;

                    if (base.DebtorID.HasValue)
                    {
                        recDebtorSectorRepo recDebtorSectorDal = new recDebtorSectorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                        List<recDebtorSector> debtorSectors = recDebtorSectorDal.GetListByDebtor(base.DebtorID.Value);

                        if (debtorSectors.Count > 0)
                        {
                            if (!string.IsNullOrEmpty(base.SubSubSectorIDs))
                            {
                                string[] datas = base.SubSubSectorIDs.Split(',');
                                debtorSectors = debtorSectors.Where(m => datas.Contains(m.SubSubSectorID.ToString())).ToList();
                            }

                            var debtorSectorId = debtorSectors.FirstOrDefault().DebtorSectorID;

                            obj.DebtorSectorID = debtorSectorId;
                            objBilling.DebtorSectorID = debtorSectorId;
                            objInvoice.DebtorSectorID = debtorSectorId;
                        }
                    }

                    // For InvoiceNo format                
                    var sectorCode = jo["SectorCode"].ToString();
                    var subSectorCode = jo["SubSectorCode"].ToString();

                    bool isSaved = recCorporateActionDal.Save(obj, objInvoice, objInvoiceDetail, objBilling, sectorCode, subSectorCode);

                    //if (obj.CorporateActionTypeID.HasValue) 
                    //{
                    //    if (obj.CorporateActionTypeID.Value.Equals(1) || obj.CorporateActionTypeID.Value.Equals(2)) // Penggabungan / Peleburan Perusahaan Terbuka || Pengambilalihan Perusahaan Terbuka
                    //    {
                    //        if (isSaved)
                    //        {
                    //            recDebtorRepo debtorDal = new recDebtorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                             
                    //            recDebtor debtor = new recDebtor();                                
                    //            debtor.DebtorID = obj.DebtorID.Value;
                    //            debtor.IsActive = false;
                    //            debtor.UpdatedBy = base.UserLoggedIn;
                    //            debtor.UpdatedDate = DateTime.Now;
                                
                    //            debtorDal.SetActivation(debtor);

                    //            SIPO.Library.DataAccess.Administration.UserManagement.recUserRepo userDal = new SIPO.Library.DataAccess.Administration.UserManagement.recUserRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);                                                                
                                
                    //            recUser user = new recUser();
                    //            user.IsActive = false;
                    //            user.DebtorID = debtor.DebtorID;
                    //            user.UpdatedBy = base.UserLoggedIn;
                    //            user.UpdatedDate = DateTime.Now;
                    //            userDal.SetActivation(user);
                    //        }

                    //    }
                    //}

                    helper.Message = "Data berhasil disimpan!";
                    helper.Data = obj.InvoiceNo;
                    helper.IsSuccess = true;
                }
                catch (Exception ex)
                {
                    helper.IsSuccess = false;
                    helper.Message = ex.Message;
                }
                finally
                {
                    recLog log = new recLog();
                    log.LogEvent = "Insert";
                    log.LogMessage = helper.Message;
                    log.LogSource = "recCorporateActionhandler.ashx";
                    log.CreatedBy = base.UserLoggedIn;
                    log.CreatedDate = DateTime.Now;
                    logDal.Save(log);

                }
            }
            else
            {
                helper.IsSuccess = false;
                if (isExpired)
                    helper.Message = "Captcha telah habis masa waktunya, silahkan masukan yang baru !";
                else
                    helper.Message = "Anda salah memasukkan Captcha !";
                
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }

        private string Update(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                recCorporateAction obj = new recCorporateAction();
                obj.CorporateActionID = (int)jo["CorporateActionID"];
                if (jo["CorporateActionTypeID"].ToString() != "")
                    obj.CorporateActionTypeID = (short)jo["CorporateActionTypeID"];
                if (jo["DebtorID"].ToString() != "")
                    obj.DebtorID = (int)jo["DebtorID"];
                if (jo["ImpositionValue"].ToString() != "")
                    obj.ImpositionValue = Helper.ToDecimal(jo["ImpositionValue"].ToString(), System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);

                if (jo["DebtorSectorID"].ToString() != "")
                    obj.DebtorSectorID = (int)jo["DebtorSectorID"];

                if (jo["ImpositionBaseID"].ToString() != "")
                    obj.ImpositionBaseID = (short)jo["ImpositionBaseID"];

                obj.CorporateName = (string)jo["CorporateName"];
                obj.CorporateSector = (string)jo["CorporateSector"];

                obj.NPWP = (string)jo["NPWP"];
                obj.Address1 = (string)jo["Address1"];
                obj.Address2 = (string)jo["Address2"];
                obj.Address3 = (string)jo["Address3"];
                if (jo["RegionID"].ToString() != "")
                    obj.RegionID = Convert.ToInt32(jo["RegionID"]);
                if (jo["CityID"].ToString() != "")
                    obj.CityID = Convert.ToInt32(jo["CityID"]);
                obj.ZipCode = (string)jo["ZipCode"];
                obj.Email = (string)jo["Email"];
                obj.Phone = (string)jo["Phone"];
                obj.Fax = (string)jo["Fax"];
                obj.Website = (string)jo["Website"];

                obj.BillingNo = (string)jo["BillingNo"];
                obj.InvoiceNo = (string)jo["InvoiceNo"];
                obj.InvoiceDate = (DateTime)jo["InvoiceDate"];
                obj.CorporateActionDate = (DateTime)jo["CorporateActionDate"];

                obj.UpdateDate = DateTime.Now;
                obj.UpdateBy = base.UserLoggedIn;

                recCorporateActionDal.Update(obj);

                helper.Message = "Data berhasil di ubah !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "recCorporateActionhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }

        private string Delete(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var strId = (string)jo["CorporateActionID"];

                string[] ids = strId.Split(',');
                foreach (string id in ids)
                {
                    int intID = Convert.ToInt32(id);
                    recCorporateActionDal.Delete(intID);
                }

                helper.IsSuccess = true;
                helper.Message = "Data berhasil di hapus !";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = helper.Message;
                log.LogSource = "srecRegistrationhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }

        private string GetData(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            if (!string.IsNullOrEmpty(parameters)) // If CurrentUser while using filter on Grid
            {
                if (base.DebtorID.HasValue) // User Is Debitur
                {
                    parameters += " AND recDebtor.DebtorID = " + base.DebtorID;
                    if (!string.IsNullOrEmpty(base.SubSubSectorIDs))
                    {
                        parameters += " AND recSubSubSector.SubSubSectorID IN (" + base.SubSubSectorIDs + ")";
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(base.SubSubSectorIDs))
                    {
                        parameters += " AND (recSubSubSector.SubSubSectorID IN (" + base.SubSubSectorIDs + ") OR recCorporateAction.DebtorSectorID IS NULL)";
                    }
                }
            }
            else
            {
                if (base.DebtorID.HasValue) // User Is Debitur
                {
                    parameters = " WHERE recDebtor.DebtorID = " + base.DebtorID;
                    if (!string.IsNullOrEmpty(base.SubSubSectorIDs))
                    {
                        parameters += " AND recSubSubSector.SubSubSectorID IN (" + base.SubSubSectorIDs + ")";
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(base.SubSubSectorIDs))
                    {
                        parameters = " WHERE (recSubSubSector.SubSubSectorID IN (" + base.SubSubSectorIDs + ") OR recCorporateAction.DebtorSectorID IS NULL)";
                    }
                }
            }

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recCorporateAction.Fields.CorporateActionID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recCorporateAction> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(recCorporateActionDal.SelectScalar(SQL.Function.Aggregate.Count, recCorporateAction.Fields.CorporateActionID, parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = recCorporateActionDal.GetList(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "recCorporateActionhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}